package com.example.plugin.ui;

import com.example.plugin.config.DefaultTemplate;
import com.example.plugin.util.TemplateUtil;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.impl.NewProjectUtil;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.EditorSettings;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.*;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBList;
import com.intellij.util.LocalTimeCounter;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 模板面板
 *
 * @author lipan
 * @date 2022/1/16 21:01
 * @email 13160080997@163.com
 */
public class TemplatePanel extends JPanel {

    private List<DefaultTemplate> list;

    private JPanel leftPanel;

    private JPanel rightPanel;

    private Editor editor;

    private JBList<String> itemList;

    public TemplatePanel(){

    }

    public TemplatePanel(List<DefaultTemplate> list){
        this.list = list;
        leftPanel = new JPanel(new BorderLayout());
        List<String> data = new ArrayList<>();
        list.forEach(item -> data.add(item.getName()));
        itemList = new JBList(data);
        leftPanel.setPreferredSize(new Dimension(150,550));
        itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        itemList.setPreferredSize(new Dimension(-1,-1));
        if(data.size()>0){
            itemList.setSelectedIndex(0);
        }
        itemList.addListSelectionListener( listener -> {
            String selectedValue = itemList.getSelectedValue();
            DefaultTemplate selectedItem = getSelectedItem(selectedValue);
            if(null==selectedItem){
                return;
            }
            this.addTemplateContent(selectedItem);
        });
        leftPanel.add(itemList, BorderLayout.CENTER);
        leftPanel.setBorder(new CustomLineBorder(1, 1, 1, 1));

        // 右边面板
        rightPanel = new JPanel(new BorderLayout());
        rightPanel.setPreferredSize(new Dimension(350,550));
//        rightPanel.setBorder(new LineBorder(Color.lightGray,1));
        this.setLayout(new BorderLayout(5,5));
        this.add(leftPanel,BorderLayout.WEST);
        this.add(rightPanel,BorderLayout.CENTER);
        if(data.size()>0){
            String selectedValue = itemList.getSelectedValue();
            DefaultTemplate selectedItem = getSelectedItem(selectedValue);
            if(null!=selectedItem){
                this.addTemplateContent(selectedItem);
            }
        }

    }

    public DefaultTemplate getSelectedItem(){
        String selectedValue = itemList.getSelectedValue();
        DefaultTemplate selectedItem = getSelectedItem(selectedValue);
        return selectedItem;
    }

    private DefaultTemplate getSelectedItem(String selectedValue) {
        for(DefaultTemplate template1:list){
            if(template1.getName().equals(selectedValue)){
                return template1;
            }
        }
        return null;
    }

    private void addTemplateContent(DefaultTemplate template){
        Project project = ProjectManager.getInstance().getDefaultProject();
        EditorFactory editorFactory = EditorFactory.getInstance();
        if (editor != null) {
            editorFactory.releaseEditor(editor);
        }
        String name = template.getName();
        String[] split = name.split("\\.");
        String prefix = split[0];
        String fileTypeStr = "";
        if("sqlMap".equals(prefix)){
            fileTypeStr = "xml";
        }else{
            fileTypeStr = "java";
        }
        FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(fileTypeStr);
        LightVirtualFile virtualFile = new LightVirtualFile(template.getName(), fileType, template.getText(), LocalTimeCounter.currentTime());
        virtualFile.putUserData(FileTemplateManager.DEFAULT_TEMPLATE_PROPERTIES, FileTemplateManager.getInstance(project).getDefaultProperties());

        Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
        editor = editorFactory.createEditor(document,project);
        EditorSettings editorSettings = editor.getSettings();
        editorSettings.setCaretRowShown(true);
        // 关闭虚拟空间
        editorSettings.setVirtualSpace(false);
        // 关闭标记位置（断点位置）
        editorSettings.setLineMarkerAreaShown(false);
        // 关闭缩减指南
        editorSettings.setIndentGuidesShown(false);
        // 显示行号
        editorSettings.setLineNumbersShown(true);
        // 支持代码折叠
        editorSettings.setFoldingOutlineShown(true);
        // 附加行，附加列（提高视野）
        editorSettings.setAdditionalColumnsCount(3);
        editorSettings.setAdditionalLinesCount(3);
        // 不显示换行符号
        editorSettings.setCaretRowShown(false);
        //高亮
//        String fileName = TemplateUtil.class.getClassLoader().getResource(template.getName()).getPath();
//        String fullName = fileName.substring(0,fileName.lastIndexOf(".")+1)+fileTypeStr;
//        ((EditorEx) editor).setHighlighter(EditorHighlighterFactory.getInstance().createEditorHighlighter(project, new LightVirtualFile(fullName,template.getText())));
        rightPanel.removeAll();
        this.rightPanel.add(editor.getComponent());
    }

    public JPanel getLeftPanel() {
        return leftPanel;
    }

    public void setLeftPanel(JPanel leftPanel) {
        this.leftPanel = leftPanel;
    }

    public JPanel getRightPanel() {
        return rightPanel;
    }

    public void setRightPanel(JPanel rightPanel) {
        this.rightPanel = rightPanel;
    }

    public Editor getEditor() {
        return editor;
    }

    public void setEditor(Editor editor) {
        this.editor = editor;
    }
}
